package com.yanyuan.mybaits.config;

import com.yanyuan.mybaits.config.xml.Command;
import com.yanyuan.mybaits.config.xml.Mapper;
import com.yanyuan.mybaits.config.xml.XmlBuilder;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.Map;

/**
 * @Description mapper执行方法
 * @Author yanyuan
 * @Date 14:23 2020/3/18
 * @Version 1.0
 **/
@Slf4j
public class MapperMethod {

    private final Method interfaceMethod;
    private final Map<Method, Command> methodCache;


    public MapperMethod(Method interfaceMethod, Map<Method, Command> methodCache) {
        this.interfaceMethod = interfaceMethod;
        this.methodCache = methodCache;
    }

    public Object execute(SqlSession sqlSession, Object[] args) throws RuntimeException {
        String sql = null;
        Command command = methodCache.get(interfaceMethod);
        if(command == null){
            throw new RuntimeException(MessageFormat.format("mapper config {0} {1} not find ", interfaceMethod.getDeclaringClass().getName(),  interfaceMethod.getName()));
        }
        sql = MessageFormat.format(command.getContent(), args);
        if(sql == null){
            throw new RuntimeException(MessageFormat.format("method {} not find sql ", interfaceMethod.getName()));
        }
        log.info("execute sql : {}", sql);
        return null;
    }
}
